import {validateParameter} from "@/app/utils/validation";
import ToastUtil from "@/app/utils/toastUtil";
import cookie from "react-cookies";
import {inFifteenMinutes, Token, UserName} from "@/app/constants/authTokenConstants";
import {encodeToBase64} from "next/dist/build/webpack/loaders/utils";
import useRequest from "@/app/utils/axiosRequest";
import axios from "axios";

/**
 * 用户登录
 * @param username
 * @param password
 * @param setLoading
 * @constructor
 */
export default async function LoginService({username, password, setLoading}: any) {

    //axios统一配置中心
    const axiosInstance = useRequest();
    /*参数验证*/
    if (!validateParameter({username, password})) {
        return false;
    }
    setLoading(true)
    await axiosInstance.post('user/user/login',
        {
            username: username,
            password: password
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        }
    ).then(response => {
            const data = response.data;
            if (data.status) {
                ToastUtil(data.message, '☺️', "success")
                /*存储Token和UserName*/
                cookie.save(Token, data.data.token, {expires: inFifteenMinutes, path: '/'});
                cookie.save(UserName, encodeToBase64(username), {expires: inFifteenMinutes, path: '/'});/*Base64编码存储*/
                /*进入主页*/
                window.location.reload()
                return true;
            }
            ToastUtil(data.message, '😶', "error")
            cookie.remove(Token, {path: '/'})
            cookie.remove(UserName, {path: '/'})
            return false;
        }
    ).catch(error => {
            ToastUtil(error.message, '🤬', "error")
            return false;
        }
    ).finally(() => {
        /*更新Progress状态*/
        setLoading(false)
    })
}